using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using Cysharp.Threading.Tasks;
using UnityEngine;

namespace FpFrame
{
    [CreateAssetMenu(menuName = "FpFrame/ConfigManager")]
    public class ConfigManager : CoreManager
    {
        private readonly Dictionary<Type, object> _configs = new Dictionary<Type, object>();
        private string _persistentPath;
        private string _streamingPath;

        public override UniTask InitAsync()
        {
            _persistentPath = Path.Combine(Application.persistentDataPath, "Config");
            _streamingPath = Path.Combine(Application.streamingAssetsPath, "Config");
            return UniTask.CompletedTask;
        }

        public async UniTask<T> LoadAsync<T>() where T : new()
        {
            Type t = typeof(T);
            if (_configs.TryGetValue(t, out var cached))
                return (T)cached;
            
            string persistentFile = Path.Combine(_persistentPath, $"{t.Name}.json");

            if (File.Exists(persistentFile))
            {
                string json = await File.ReadAllTextAsync(persistentFile);
                return JsonUtility.FromJson<T>(json);
            }

            string streamingFile = Path.Combine(_streamingPath, $"{t.Name}.json");
            if (File.Exists(streamingFile))
            {
                string json = await File.ReadAllTextAsync(streamingFile);
                T data = JsonUtility.FromJson<T>(json);
                await SaveAsync(data);
                return data;
            }

            T defaultData = new T();
            await SaveAsync(defaultData);
            return defaultData;
        }

        private async UniTask SaveAsync<T>(T data) where T : new()
        {
            Type t = data.GetType();
            _configs[t] = data;

            string path = Path.Combine(_persistentPath, $"{t.Name}.json");
            Directory.CreateDirectory(Path.GetDirectoryName(path) ?? string.Empty);

            var json = JsonUtility.ToJson(data, true);
            await File.AppendAllTextAsync(path, json);
        }
    }
}